package com.veal98.tree;

import com.veal98.bean.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BinaryTreeLevelOrderTraversal_102 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        // 存储遍历结果
        List<List<Integer>> res = new ArrayList<>();
        // 辅助队列
        Queue<TreeNode> queue = new LinkedList<>();

        if (root == null) {
            return res;
        }

        while (!queue.isEmpty()) {
            // 存储每层的节点
            List<Integer> line = new ArrayList<>();
            // 当前层的节点个数
            int size = queue.size();

            for (int i = 0; i < size; i ++) {
                // 当前层节点存进 res
                TreeNode cur = queue.poll();
                line.add(cur.val);

                // 下一层节点入队
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }

            res.add(line);
        }

        return res;
    }
}
